package arduino.comm.connection;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

public class SerialReader implements SerialPortEventListener {
    private final BufferedReader _inBufferedReader;
    private String _inputData;
    private boolean _close = false;

    // Constructor
    public SerialReader(InputStream inputStream) {
	_inBufferedReader = new BufferedReader(new InputStreamReader(inputStream), 5);
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
	String rawInput = null;
	switch (event.getEventType()) {
	case SerialPortEvent.BI:
	case SerialPortEvent.CD:
	case SerialPortEvent.CTS:
	case SerialPortEvent.DSR:
	case SerialPortEvent.FE:
	case SerialPortEvent.OE:
	case SerialPortEvent.PE:
	case SerialPortEvent.RI:
	case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
	    break;
	case SerialPortEvent.DATA_AVAILABLE:
	    try {
		System.out.println("Begin receiving:");
		while (!_close && (rawInput = _inBufferedReader.readLine()) != null) {
		    System.out.println(new Date() + ": " + rawInput);
		    // _inputData += rawInput;
		}
	    } catch (IOException e) {
		e.printStackTrace();
		try {
		    _inBufferedReader.close();
		} catch (IOException ex) {
		    ex.printStackTrace();
		}
		// System.exit(-1);
	    }
	    break;
	default:
	    break;
	}
    }

    public String getInputData() {
	return _inputData;
    }

    public boolean isClose() {
	return _close;
    }

    public void setClose(boolean close) {
	_close = close;
    }

    public void close() {
	_close = true;
    }
}